package com.alm.token.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.RechargeAddressData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BaseView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import baibeiwallet.WalletDaoUtils;
import baibeiwallet.model.ETHWallet3;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

//import com.uuzuche.lib_zxing.activity.CodeUtils;
//import com.zxing.support.library.qrcode.QRCodeEncode;

public class TransferQrCodeActivity_new extends BaseActivity implements BaseView<RechargeAddressData> {
    @BindView(R.id.tv_walletname)
    TextView tvWalletname;
    @BindView(R.id.img_adressqrcode)
    ImageView imgAdressqrcode;
    @BindView(R.id.tv_adressshow)
    TextView tvAdressshow;
    @BindView(R.id.tv_adressshow2)
    TextView tvAdressshow2;
    @BindView(R.id.tv_adressshow2msg)
    TextView tvAdressshow2Msg;
    @BindView(R.id.tv_copyadress)
    TextView tvCopyadress;
    @BindView(R.id.tv_copyadress2)
    TextView tvCopyadress2;
    @BindView(R.id.tv_savexiangche)
    TextView tvSavexiangche;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.img_more)
    ImageView imgMore;
    @BindView(R.id.rly_xrpbody)
    RelativeLayout rlyXrpBody;

    private String walletAddress = "", walletAddressTag = "";
    private int bizhongType = 0;
    private String bizhongName = "ETH";
    //    private QRCodeEncode.Builder builder;
    private Bitmap qrCodeBitmap = null;
    private Map<String, String> bizhongAdressMap = new HashMap<>();
    private String rechargeAddress;
    private boolean isJiedianWallet;

    ETHWallet3 ethWallet;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_transfer_qrcode;
    }

    @Override
    protected void initVariables() {
        isJiedianWallet = getIntent().getBooleanExtra("jiedianwallet", false);
        bizhongType = getIntent().getIntExtra("bizhongType", 0);
        bizhongName = getIntent().getStringExtra("bizhongName");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item10));
    }

    @Override
    protected void loadData() {
        if (!isJiedianWallet)
            preenter.getRechargeAddress(String.valueOf(bizhongType));
        else {
            ethWallet = WalletDaoUtils.getCurrent();
            mathInitView();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_walletname:
                showPopupMenu2(tvWalletname);
                break;
        }

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void getData(RechargeAddressData rechargeAddressData) {

        if (rechargeAddressData.getStatus() == 0 && rechargeAddressData.getData() != null) {
            /**
             * address : 17681826025
             * name : MIO
             * id : 2
             */

            rechargeAddress = rechargeAddressData.getData().getAddress();
            mathInitView();
            imgMore.setVisibility(View.GONE);

        } else {
            showToast(rechargeAddressData.getMsg());
        }

    }

    public void mathInitView() {

        if (!isJiedianWallet) {
            if (rechargeAddress != null) {
                walletAddress = rechargeAddress;
                tvWalletname.setText(bizhongName + " wallet");


                if (!TextUtils.isEmpty(bizhongName) && (bizhongName.equalsIgnoreCase("XRP") || bizhongName.equalsIgnoreCase("EOS")
                ||bizhongName.equalsIgnoreCase("HXRP") || bizhongName.equalsIgnoreCase("HEOS"))) {
                    rlyXrpBody.setVisibility(View.VISIBLE);

                    LogUtil.e("walletAddress=" + walletAddress);
                    String[] adress = walletAddress.split("_");
                    LogUtil.e("adress.size=" + adress.length);
                    walletAddress = adress[0];
                    walletAddressTag = adress[1];
                    tvAdressshow2.setText("Tag：" + walletAddressTag);
                    tvAdressshow2Msg.setText(getString(R.string.wallet_hint_xrpmsg, bizhongName));
                } else {
                    rlyXrpBody.setVisibility(View.GONE);
                    walletAddressTag = "";
                    tvAdressshow2.setText("Tag：" + walletAddressTag);
                    tvAdressshow2Msg.setText(getString(R.string.wallet_hint_bishow2msg, EmptyUtils.isNotEmpty(bizhongName) ? bizhongName : ""));
                }

                LogUtil.e("88+" + walletAddress);
                if (TextUtils.isEmpty(walletAddress)) {
                    showToast(getString(R.string.currency_hint1_warn));
                }
            } else {
                showToast(getString(R.string.currency_hint1_warn));
            }
        } else {
            walletAddress = ethWallet.getAddress();
            tvWalletname.setText(ethWallet.getName().indexOf("wallet") != -1 ? ethWallet.getName() : ethWallet.getName() + " wallet");
            imgMore.setVisibility(View.GONE);
        }

        if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
            tvUsername.setText(MyApp.getUserData().getData().getUser().getLoginname() + "");
        }
        String str1 = "", str2 = "";
        if (!walletAddress.isEmpty()) {
            walletAddress.length();
//            walletAddress="12345678";
//            walletAddress="123456789";
            str1 = walletAddress.substring(0, walletAddress.length() % 2 == 0 ? walletAddress.length() / 2 : (walletAddress.length() - 1) / 2);
            str2 = walletAddress.substring((walletAddress.length() % 2 == 0 ? walletAddress.length() / 2 : (walletAddress.length() - 1) / 2));
        }
        tvAdressshow.setText(str1 + "\n" + str2);
        initAddressQRCode();
    }

    @Override
    public void onError(String error) {

    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @OnClick({R.id.tv_copyadress, R.id.tv_savexiangche, R.id.tv_copyadress2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_copyadress:
                if (walletAddress.isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress();
                break;
            case R.id.tv_copyadress2:
                if (walletAddressTag.isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress1();
                break;
            case R.id.tv_savexiangche:
                if (qrCodeBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }

                //存储权限
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (saveImageToGallery(TransferQrCodeActivity_new.this, qrCodeBitmap, tvWalletname.getText() + CommonUtil.getStringDate() + getString(R.string.profile_hint_item25))) {
                                        showToast(getString(R.string.profile_hint_item15));
                                        tvSavexiangche.setText(getString(R.string.profile_hint_item16));
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;
        }
    }

    public void showPopupMenu2(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();

        if (bizhongAdressMap.get("ETH") != null) {
            menu.add("ETH" + " wallet");
        }

        for (String key : bizhongAdressMap.keySet()) {
            if (!key.equalsIgnoreCase("ETH")) {
                menu.add(key + " wallet");
            }
        }
//        menu.add("ETH wallet");
//        menu.add("USDT wallet");

        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getTitle().toString().indexOf(tvWalletname.getText().toString()) == -1) {
//                    if (item.getTitle().toString().indexOf("ETH wallet") != -1) {
//                        bizhongType = 1;
//                    } else {
//                        showToast(getString(R.string.currency_hint1_warn));
////                        bizhongType = 3;
//                    }

                    bizhongName = item.getTitle().toString().replace(" wallet", "");
                    mathInitView();
                }

                return true;
            }
        });
        popupMenu.show();
    }

    private void initAddressQRCode() {


//        builder = new QRCodeEncode.Builder();
//        builder.setBackgroundColor(getResources().getColor(R.color.white))
//                .setOutputBitmapHeight(CommonUtil.dip2px(this, 144))
//                .setOutputBitmapWidth(CommonUtil.dip2px(this, 144))
//                .setOutputBitmapPadding(CommonUtil.dip2px(this, 1));
//        qrCodeBitmap = builder.build().encode(walletAddress);

//         qrCodeBitmap = CodeUtils.createImage(walletAddress,
//                CommonUtil.dip2px(this, 144),
//                CommonUtil.dip2px(this, 144),
//                null);
        qrCodeBitmap = CodeCreator.createQRCode(walletAddress,
                CommonUtil.dip2px(this, 144),
                CommonUtil.dip2px(this, 144),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

//        imgAdressqrcode.setBackgroundColor(getResources().getColor(R.color.white));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);
//        GlideApp.with(this).load(qrCodeBitmap).into(imgAdressqrcode);
//        GlideImageLoader.loadBmpImage(ivGatheringQrcode, qrCodeBitmap, -1);
    }

    private void copyWalletAddress() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", walletAddress);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
//        tvCopyadress.setText(getString(R.string.profile_hint_item14));
    }

    private void copyWalletAddress1() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", walletAddressTag);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
//        tvCopyadress2.setText(getString(R.string.profile_hint_item14));
    }


    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
